package com.example.protocol;

import com.example.common.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClient {
    public String send(String hostName, Integer port, Invocation invocation) {
        // 发Http请求
        try {
            URL url = new URL("http", hostName, port,"/");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            OutputStream os = httpURLConnection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);

            oos.writeObject(invocation);
            oos.flush();
            oos.close();

            InputStream is = httpURLConnection.getInputStream();
            String result = IOUtils.toString(is);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }
}
